<template>
  <a-table
    bordered
    ref="table"
    size="small"
    :columns="columns"
    :row-key="(row) => row.resource"
    :data-source="data"
    :pagination="false"
    :loading="loading"
  >
    <template slot="serial" slot-scope="text, item, index">
      <a-checkbox
        :value="index"
        :checked="item.checked"
        @change="onCheckAllChange(item, $event)"
      ></a-checkbox>
    </template>

    <template slot="permissions" slot-scope="text, item">
      <template v-if="item.permissions">
        <a-checkbox
          style="width: 300px"
          v-for="o in item.permissions"
          @change="onCheckChange(item, o, $event)"
          :key="o.key"
          :value="o.key"
          :checked="o.checked"
          >{{ o.keyName }}</a-checkbox
        >
      </template>
    </template>
  </a-table>
</template>
<script>
import { queryDataPermission } from "@/api/sys/permission/dataPermission";
export default {
  props: {
    role: {
      type: Object,
    },
  },
  data() {
    return {
      loading: false,
      data: [],
      // 内容勾选
      ckOperationList: [],
      checkAll: false,
      // 表头
      columns: [
        {
          title: "#",
          width: "100px",
          scopedSlots: { customRender: "serial" },
        },
        {
          width: "160px",
          title: "资源名称",
          dataIndex: "resource",
        },
        {
          title: "权限标识",
          dataIndex: "permissions",
          scopedSlots: { customRender: "permissions" },
        },
      ],
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      //加载列表
      let that = this;
      this.spinning = false;
      queryDataPermission({ roleId: this.role.id })
        .then((res) => {
          that.data = res.data;
          that.spinning = false;
        })
        .catch((error) => {
          that.spinning = false;
        });
    },
    // 单个Operation操作
    onCheckChange(row, item, e) {
      item.checked = e.target.checked;
      if (e.target.checked) {
        // 勾选
        row.checked = e.target.checked;
      } else {
        // 取消勾选，查看是否都取消选中，都取消，则父级也取消
        row.checked = row.permissions.find((m) => m.checked)?true:false;
      }
    },
    // 选择每行所有操作
    onCheckAllChange(item, e) {
      item.checked = e.target.checked;
      if (item.permissions) {
        item.permissions.forEach((element) => {
          element.checked = e.target.checked;
        });
      }
      if (item.children) {
        // 所有子项都选中
        item.children.forEach((element) => {
          this.onCheckAllChange(element, e);
        });
      }
    },
  },
};
</script>